package com.lgy.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lgy.common.SessionUtils;
import com.lgy.model.entity.SysUser;
import com.lgy.service.ISysUserService;
import com.lgy.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/sys")
public class SysController {
    @Autowired
    private ISysUserService sysUserService;

    @RequestMapping("/login")
    public ResponseResult login(HttpServletRequest request, String account, String password){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("login_name",account);
        SysUser sysUser = sysUserService.getOne(wrapper);
        if(null != sysUser && sysUser.getPassword().equals(password)) {
            //将用户信息存在session中
            SessionUtils.setAttr(request,SessionUtils.SESSION_USER, sysUser);
            return ResponseResult.success(sysUser.getUserName());
        }
        return ResponseResult.fail();
    }

    @RequestMapping("/getLoginInfo")
    public ResponseResult loginInfo(HttpServletRequest request){
        SysUser sysUser = (SysUser) SessionUtils.getAttr(request,SessionUtils.SESSION_USER);
        if(null != sysUser) {
            return ResponseResult.success(sysUser.getUserName());
        }
        return ResponseResult.fail();
    }

    @RequestMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SessionUtils.removeAttr(request,SessionUtils.SESSION_USER);
        response.sendRedirect("/login.html");
    }
}
